package org.ysh.controller;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.ysh.core.annotation.ResourceEx;
import org.ysh.core.cache.Constants;
import org.ysh.core.web.TableDataInfo;
import org.ysh.domain.User;
import org.ysh.service.UserService;
import org.ysh.vo.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

import static org.ysh.domain.User.USER_STATUS_DISABLE;
import static org.ysh.domain.User.USER_STATUS_NORMAL;

@Slf4j
@Controller
@RequestMapping("/system")
public class UserController extends BaseController{

    @Resource
    private UserService userService;

    @ResourceEx(name = "用户管理",code = "system.user",description = "用户管理",icon = "fa fa-user",type = 0,sort = 1,parentCode = "system")
    @RequestMapping("/user")
    public String user(){
        return "system/user/list";
    }


    /**
     * 用户基本信息
     * @return
     */
    @GetMapping("/user/settings")
    public String userSettings(){
        return "system/user-settings";
    }


    /**
     * 更新用户基本信息
     * @return R
     */
    @PostMapping("/user/settings")
    @ResponseBody
    public R<?> updateUserSettings(User user, HttpSession session){
        User curUser = (User)session.getAttribute(Constants.CURRENT_USER);
        curUser.setRealName(user.getRealName());
        curUser.setEmail(user.getEmail());
        curUser.setPhone(user.getPhone());
        userService.update(curUser);
        return R.ok();
    }


    /**
     * 修改用户密码
     */
    @GetMapping("/user/password")
    public String updateUserPassword(){
        return "system/user-password";
    }

    @PostMapping("/user/password")
    @ResponseBody
    public R<String> updateUserPassword(String old_password,String new_password){
        try{
            userService.updatePassword(old_password,new_password);
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok();
    }




    @ResourceEx(name = "列表",code = "system.user.list",description = "用户管理-用户列表",icon = "fa fa-user",type = 1,sort = 0,parentCode = "system.user",permission = "system:user:list")
    @RequiresPermissions(value = "system:user:list")
    @GetMapping("/user/list")
    @ResponseBody
    public TableDataInfo list(User user){
        startPage();
        TableDataInfo dataTable = getDataTable(userService.findByPage(user));
        List<User> data = (List<User>)dataTable.getData();
        dataTable.setData(userService.toUserVos(data));
        return dataTable;
    }

    @RequiresPermissions(value = "system:user:add")
    @ResourceEx(name = "新增",code = "system.user.add",description = "用户管理-新增用户",icon = "fa fa-plus-square",type = 1,sort = 1,permission = "system:user:add",parentCode = "system.user")
    @GetMapping("/user/add")
    public String add(){
        return "system/user/add";
    }

    @RequiresPermissions(value = "system:user:add")
    @PostMapping("/user/add")
    @ResponseBody
    public R<?> add(User user){
        try{
            userService.saveUserWithRoleIds(user);
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    @RequiresPermissions(value = "system:user:edit")
    @ResourceEx(name = "编辑",code = "system.user.edit",description = "用户管理-编辑用户",icon = "fa fa-edit",type = 1,sort = 2,permission = "system:user:edit",parentCode = "system.user")
    @GetMapping("/user/edit")
    public ModelAndView edit(Integer id){
        if(null == id) {
            throw new RuntimeException("编辑的用户不能为空");
        }
        User user = userService.findUserWithRoleIds(id);
        if(user == null) {
            throw new RuntimeException("编辑的用户不存在");
        }
        return new ModelAndView("system/user/edit","user",user);
    }

    @RequiresPermissions(value = "system:user:edit")
    @PostMapping("/user/edit")
    @ResponseBody
    public R edit(User user){
        if(user == null) {
            return R.fail("编辑的用户不存在");
        }
        //更新用户
        userService.updateUserWithRoleIds(user);
        return R.ok();
    }

    @RequiresPermissions(value = "system:user:delete")
    @ResourceEx(name = "删除",code = "system.user.delete",description = "用户管理-删除用户",icon = "fa fa-minus-square",type = 1,sort = 3,permission = "system:user:delete",parentCode = "system.user")
    @PostMapping("/user/delete")
    @ResponseBody
    public R delete(Integer id){
        if(null == id) {
            return R.fail("删除的用户不能为空");
        }
        if(id == 1) {
            return R.fail("管理员禁止操作");
        }
        User user = userService.findById(id);
        if(user == null) {
            return R.fail("删除的用户不存在");
        }
        User currentUser = getCurrentUser();
        user.setDeleteBy(currentUser.getId());
        userService.delete(user);
        return R.ok();
    }

    @RequiresPermissions(value = "system:user:delete")
    @PostMapping("/user/batchDelete")
    @ResponseBody
    public R batchDelete(@RequestParam("ids[]") Integer[] ids){
        if(null == ids) {
            return R.fail("删除的用户不能为空");
        }
        for(Integer id : ids){
            if( id == 1) {
                return R.fail("管理员禁止操作");
            }
        }

        for(Integer id : ids){
            User user = userService.findById(id);
            if(user == null) {
                return R.fail("删除的用户不存在");
            }
            User currentUser = getCurrentUser();
            user.setDeleteBy(currentUser.getId());
            userService.delete(user);
        }

        return R.ok();
    }

    @RequiresPermissions(value = "system:user:disable")
    @ResourceEx(name = "禁用",code = "system.user.disable",description = "用户管理-禁用用户",icon = "fa fa-ban",type = 1,sort = 4,permission = "system:user:disable",parentCode = "system.user")
    @PostMapping("/user/disable")
    @ResponseBody
    public R disable(Integer id){
        if(null == id) {
            return R.fail("禁用的用户不能为空");
        }
        if(id == 1) {
            return R.fail("管理员禁止操作");
        }
        User user = userService.findById(id);
        if(user == null) {
            return R.fail("禁用的用户不存在");
        }
        User currentUser = getCurrentUser();
        user.setUpdateBy(currentUser.getId());
        user.setUpdateTime(new Date());
        user.setStatus(USER_STATUS_DISABLE);
        userService.update(user);
        return R.ok();
    }

    @RequiresPermissions(value = "system:user:enable")
    @ResourceEx(name = "启用",code = "system.user.enable",description = "用户管理-启用用户",icon = "fa fa-check",type = 1,sort = 5,permission = "system:user:enable",parentCode = "system.user")
    @PostMapping("/user/enable")
    @ResponseBody
    public R enable(Integer id){
        if(null == id) {
            return R.fail("启用的用户不能为空");
        }
        if(id == 1) {
            return R.fail("管理员禁止操作");
        }
        User user = userService.findById(id);
        if(user == null) {
            return R.fail("启用的用户不存在");
        }
        User currentUser = getCurrentUser();
        user.setUpdateBy(currentUser.getId());
        user.setUpdateTime(new Date());
        user.setStatus(USER_STATUS_NORMAL);
        userService.update(user);
        return R.ok();
    }

    @RequiresPermissions(value = "system:user:import")
    @ResourceEx(name = "导入",code = "system.user.import",description = "用户管理-导入用户",icon = "fa fa-check",type = 1,sort = 6,permission = "system:user:import",parentCode = "system.user")
    @ResponseBody
    @PostMapping("/user/importData")
    public R importData(@RequestPart("file") MultipartFile file) {
        if(file == null) {
            return R.fail("导入的文件不能为空");
        }
        try {
            List<User> users = EasyExcel.read(file.getInputStream()).head(User.class).sheet().doReadSync();
            userService.batchSave(users);
        } catch (Exception e) {
            log.error("导入用户失败",e);
            return R.fail("导入失败");
        }
        return R.ok();
    }

    @RequiresPermissions(value = "system:user:import")
    @GetMapping("/user/importData")
    public String importData(){
        return "system/user/upload";
    }

    @RequiresPermissions("system:user:initPassword")
    @ResourceEx(name = "重置密码",code = "system.user.initPassword",description = "用户管理-重置用户密码",icon = "fa fa-reset",type = 1,sort = 7,permission = "system:user:initPassword",parentCode = "system.user")
    @GetMapping("/user/initPassword")
    public ModelAndView initUserPassword(Integer id){
        // 添加用户id到ModelAndView, 用于在前端页面中获取用户id,再返回ModelAndView
        ModelAndView modelAndView = new ModelAndView("system/user/password");
        modelAndView.addObject("userId",id);
        return modelAndView;
    }

    @RequiresPermissions("system:user:initPassword")
    @PostMapping("/user/initPassword")
    @ResponseBody
    public R<String> initUserPassword(String password,Integer userId){
        userService.initUserPassword(userId,password);
        return R.ok();
    }

}
